<?php
function genPhpScript(&$aDati) {
	$nn = 0;
	foreach($aDati as $codX =>$acX) {
		$aRef = array();
		$aVarScript = array();
		$script = trim($acX['script']);
		if ($acX['flag_quad_calc'] == 'totsub') {
			$script = "// generato da flag_quad_calc == 'totsub'\r\n";
			$script .= "CAL Q_".$acX['cod_dato']." = 0";
			foreach($aDati as $codY =>$acY) {
				if ($acY['cod_dato_padre'] != $acX['cod_dato']) continue;
				$script .= " + Q_".$codY;
			}
		}
		if ($script != '') {
			$nn++;
			$nomeFunz = 'rglScrDato'.$acX['cod_dato'];
			$objParser = new rglParser;
			if(!$objParser->parse($script)) {
				$msg .= $objParser->getError()."<br>";
				continue;
			}
			$aDati[$codX]['script_php'] = $objParser->getPHPCode($nomeFunz);
			$aVarScript = $objParser->aVariables;
			foreach($aVarScript as $varX => $aVX) {
				if ($acX['cod_dato']!=substr($varX,2)) {
					$aRef[$acX['cod_dato']][] = substr($varX,2);
				}
			}
		}
	}
	foreach($aRef as $dl => $dr) {
		$sDBG = '';
		$liv = scanDatiR($dl, 1, $aRef);
		dbg_("$dl($liv) : $sDBG");
		$aDati[$dl]['livello'] = $liv;
	}
	return _t("generato codice per $nn script");
}

function scanDatiR($d,$liv, &$aRef) {
	global $sDBG;
	if (strlen($sDBG)>10000) {
		$sDBG .= " *** stop 10000 *** ";
		return $liv;
	}
	if ($liv > 20) {
		$sDBG .= "$d($liv) ";
		return $liv;
	}
	if (!isset($aRef[$d])) {
		$sDBG .= "$d($liv) ";
		return $liv;
	}
	$livMax = 0;
	foreach($aRef[$d] as $kX => $dX) {
		$livX = scanDatiR($dX,$liv+1,$aRef);
		if ($livX > $livMax) $livMax = $livX;
	}
	$sDBG .= "$d($livMax) ";
	return $livMax;
}
